package top.whysu.study.mytest;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.sun.deploy.net.HttpUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.zip.CRC32;

/**
 * 视频分包上传
 */
public class VideoUpload {


    public static void main(String[] args) {
        String fileName = "VID_20210813_111056.mp4";
        String filePath = "C:\\Users\\suwei\\Desktop\\海康\\" + fileName;
        FileInputStream objFileIS = null;
        File file = null;
        try {
            System.out.println("file = >>>> <<<<<" + filePath);
            objFileIS = new FileInputStream(filePath);
            file = new File(filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Long totalLen = file.length();

        ByteArrayOutputStream objByteArrayOS = new ByteArrayOutputStream();
        byte[] byteBufferString = new byte[10240];
        try {
            int i = 0;
            for (int readNum; (readNum = objFileIS.read(byteBufferString)) != -1; i++) {
                objByteArrayOS.write(byteBufferString, 0, readNum);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        DeviceUploadFileRequestDTONew dto = new DeviceUploadFileRequestDTONew();
        dto.setVersion("0.1");
        dto.setFileName(fileName);
        dto.setSuffix("mp4");
        dto.setTotalLen(totalLen);
        dto.setLen(totalLen);
        dto.setPosition(0L);
        dto.setData(Base64Encoder.encode(objByteArrayOS.toByteArray()));
        dto.setCheck(getCRC32(filePath));
        dto.setType(-1);
        String result = HttpRequest.post("http://127.0.0.1:9999/Esafe-Server-Web/rest/file/device/uploadFile")
                .contentType("application/json")
                .body(JSON.toJSONString(dto))
                .timeout(15*1000)
                .execute()
                .body();
        System.out.println(result);
    }

    /**
     * 文件CRC32校验
     *
     * @param filePath
     * @return
     */
    public static String getCRC32(String filePath) {
        String result = "";
        try {
            CRC32 crc32 = new CRC32();
            crc32.update(FileUtil.readBytes(filePath));
            result = crc32.getValue() + "";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}